package jmine.tec.web.wicket.component.autocomplete;

import java.io.Serializable;
import java.util.Iterator;

import jmine.tec.utils.reflection.GenericTypeResolverImpl;
import jmine.tec.web.wicket.spring.SpringBeanReference;
import bancosys.tec.persist.Persistable;
import bancosys.tec.persist.dao.BaseDAO;
import bancosys.tec.persist.dao.BaseDAOFactory;

/**
 * {@link ChoicesLoader} implementation that uses {@link BaseDAO#findByLikeNaturalKey(String)} in order to find choices
 * 
 * @author takeshi
 * @param <T> the {@link ChoicesLoader} type
 */
public class NaturalKeyChoicesLoader<T extends Persistable> implements ChoicesLoader<T>, Serializable {

    private final Class<T> type;

    /**
     * Constructor
     * 
     * @param type {@link Class}
     */
    public NaturalKeyChoicesLoader(Class<T> type) {
        this.type = type;
    }

    /**
     * If a class extend this one and by any chance freezes the generic type, this constructor will auto-discover what the type is
     */
    @SuppressWarnings("unchecked")
    protected NaturalKeyChoicesLoader() {
        this.type =
                (Class<T>) GenericTypeResolverImpl.getInstance().resolveTypeForFixedGenericType(
                        NaturalKeyChoicesLoader.class.getTypeParameters()[0], getClass());
    }

    /**
     * {@inheritDoc}
     */
    public Iterator<? extends T> getChoices(String input) {
        BaseDAO<T> dao = SpringBeanReference.forType(BaseDAOFactory.class).get().getGenericDAO(type);
        return dao.findByLikeNaturalKey(input).iterator();
    }

}
